<template>
  <div class="ai-document-demo">
    <h2>AI文档工具使用示例</h2>
    
    <div class="demo-section">
      <h3>1. 流式输出示例</h3>
      <div class="input-group">
        <el-input
          v-model="streamInput"
          type="textarea"
          :rows="3"
          placeholder="请输入您的问题..."
        ></el-input>
        <el-button 
          type="primary" 
          @click="handleStreamChat"
          :loading="streamLoading"
        >发送</el-button>
      </div>
      <div class="output-box">
        <div v-if="streamOutput" class="output-content">{{ streamOutput }}</div>
        <div v-else class="placeholder">AI回复将在这里显示...</div>
      </div>
    </div>

    <div class="demo-section">
      <h3>2. 文档生成示例</h3>
      <div class="input-group">
        <el-input v-model="docTopic" placeholder="文档主题"></el-input>
        <el-select v-model="docType" placeholder="文档类型">
          <el-option label="技术文档" value="技术文档"></el-option>
          <el-option label="产品说明" value="产品说明"></el-option>
          <el-option label="API文档" value="API文档"></el-option>
        </el-select>
        <el-select v-model="docAudience" placeholder="目标受众">
          <el-option label="开发者" value="开发者"></el-option>
          <el-option label="普通用户" value="普通用户"></el-option>
          <el-option label="技术专家" value="技术专家"></el-option>
        </el-select>
        <el-button 
          type="primary" 
          @click="handleGenerateDocument"
          :loading="docLoading"
        >生成文档</el-button>
      </div>
      <div class="output-box">
        <div v-if="documentOutput" class="output-content">{{ documentOutput }}</div>
        <div v-else class="placeholder">生成的文档将在这里显示...</div>
      </div>
    </div>

    <div class="demo-section">
      <h3>3. 文档润色示例</h3>
      <div class="input-group">
        <el-input
          v-model="polishInput"
          type="textarea"
          :rows="5"
          placeholder="请输入需要润色的文档内容..."
        ></el-input>
        <el-select v-model="polishStyle" placeholder="润色风格">
          <el-option label="专业" value="专业"></el-option>
          <el-option label="简洁" value="简洁"></el-option>
          <el-option label="详细" value="详细"></el-option>
        </el-select>
        <el-button 
          type="primary" 
          @click="handlePolishDocument"
          :loading="polishLoading"
        >润色文档</el-button>
      </div>
      <div class="output-box">
        <div v-if="polishOutput" class="output-content">{{ polishOutput }}</div>
        <div v-else class="placeholder">润色后的文档将在这里显示...</div>
      </div>
    </div>

    <div class="demo-section">
      <h3>4. 健康规划示例</h3>
      <div class="input-group">
        <div class="user-info">
          <el-input v-model="userInfo.age" placeholder="年龄"></el-input>
          <el-select v-model="userInfo.gender" placeholder="性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
          <el-input v-model="userInfo.height" placeholder="身高(cm)"></el-input>
          <el-input v-model="userInfo.weight" placeholder="体重(kg)"></el-input>
          <el-input v-model="userInfo.healthGoal" placeholder="健康目标"></el-input>
        </div>
        <el-button 
          type="primary" 
          @click="handleGenerateHealthPlan"
          :loading="healthLoading"
        >生成健康规划</el-button>
      </div>
      <div class="output-box">
        <div v-if="healthOutput" class="output-content">{{ healthOutput }}</div>
        <div v-else class="placeholder">健康规划将在这里显示...</div>
      </div>
    </div>

    <div class="config-section">
      <h3>配置</h3>
      <div class="input-group">
        <el-input 
          v-model="apiKey" 
          type="password" 
          placeholder="请输入阿里云模型工作室API Key"
          show-password
        ></el-input>
        <el-button type="success" @click="handleInitAiTool">初始化AI工具</el-button>
      </div>
      <div v-if="aiToolStatus" class="status-message" :class="aiToolStatus.type">
        {{ aiToolStatus.message }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { initAiDocumentTool, aiDocumentApi, healthAiApi } from '@/api/ai'

export default {
  name: 'AiDocumentDemo',
  setup() {
    // 状态变量
    const apiKey = ref('')
    const aiToolStatus = ref(null)
    
    // 流式输出相关
    const streamInput = ref('请介绍一下Vue 3的主要特性')
    const streamOutput = ref('')
    const streamLoading = ref(false)
    
    // 文档生成相关
    const docTopic = ref('Vue 3组件开发')
    const docType = ref('技术文档')
    const docAudience = ref('开发者')
    const documentOutput = ref('')
    const docLoading = ref(false)
    
    // 文档润色相关
    const polishInput = ref('Vue是一个流行的JavaScript框架。它有很多功能。开发者用它来构建网站。')
    const polishStyle = ref('专业')
    const polishOutput = ref('')
    const polishLoading = ref(false)
    
    // 健康规划相关
    const userInfo = reactive({
      age: '',
      gender: '',
      height: '',
      weight: '',
      healthGoal: ''
    })
    const healthOutput = ref('')
    const healthLoading = ref(false)
    
    // 初始化AI工具
    const handleInitAiTool = () => {
      if (!apiKey.value) {
        ElMessage.error('请输入API Key')
        return
      }
      
      const success = initAiDocumentTool(apiKey.value)
      if (success) {
        aiToolStatus.value = {
          type: 'success',
          message: 'AI工具初始化成功'
        }
      } else {
        aiToolStatus.value = {
          type: 'error',
          message: 'AI工具初始化失败'
        }
      }
    }
    
    // 处理流式聊天
    const handleStreamChat = () => {
      if (!streamInput.value.trim()) {
        ElMessage.warning('请输入问题')
        return
      }
      
      streamLoading.value = true
      streamOutput.value = ''
      
      const messages = [
        { role: 'user', content: streamInput.value }
      ]
      
      aiDocumentApi.streamChat({
        messages,
        onChunk: (chunk) => {
          streamOutput.value += chunk
        },
        onComplete: () => {
          streamLoading.value = false
        },
        onError: (error) => {
          streamLoading.value = false
          ElMessage.error('请求失败: ' + error.message)
        }
      })
    }
    
    // 处理文档生成
    const handleGenerateDocument = () => {
      if (!docTopic.value.trim() || !docType.value || !docAudience.value) {
        ElMessage.warning('请填写完整的文档信息')
        return
      }
      
      docLoading.value = true
      documentOutput.value = ''
      
      aiDocumentApi.generateDocument({
        topic: docTopic.value,
        type: docType.value,
        audience: docAudience.value,
        options: {
          stream: true,
          onChunk: (chunk) => {
            documentOutput.value += chunk
          },
          onComplete: () => {
            docLoading.value = false
          },
          onError: (error) => {
            docLoading.value = false
            ElMessage.error('文档生成失败: ' + error.message)
          }
        }
      })
    }
    
    // 处理文档润色
    const handlePolishDocument = () => {
      if (!polishInput.value.trim() || !polishStyle.value) {
        ElMessage.warning('请输入文档内容并选择润色风格')
        return
      }
      
      polishLoading.value = true
      polishOutput.value = ''
      
      aiDocumentApi.polishDocument({
        content: polishInput.value,
        style: polishStyle.value,
        options: {
          stream: true,
          onChunk: (chunk) => {
            polishOutput.value += chunk
          },
          onComplete: () => {
            polishLoading.value = false
          },
          onError: (error) => {
            polishLoading.value = false
            ElMessage.error('文档润色失败: ' + error.message)
          }
        }
      })
    }
    
    // 处理健康规划生成
    const handleGenerateHealthPlan = () => {
      if (!userInfo.age || !userInfo.gender || !userInfo.height || !userInfo.weight || !userInfo.healthGoal) {
        ElMessage.warning('请填写完整的用户信息')
        return
      }
      
      healthLoading.value = true
      healthOutput.value = ''
      
      // 模拟健康数据
      const healthData = {
        bloodPressure: '120/80',
        heartRate: 72,
        sleepHours: 7,
        exerciseMinutes: 30
      }
      
      healthAiApi.generateHealthPlan({
        userInfo,
        healthData,
        options: {
          stream: true,
          onChunk: (chunk) => {
            healthOutput.value += chunk
          },
          onComplete: () => {
            healthLoading.value = false
          },
          onError: (error) => {
            healthLoading.value = false
            ElMessage.error('健康规划生成失败: ' + error.message)
          }
        }
      })
    }
    
    // 组件挂载时尝试从localStorage获取API Key
    onMounted(() => {
      const savedApiKey = localStorage.getItem('aiApiKey')
      if (savedApiKey) {
        apiKey.value = savedApiKey
        handleInitAiTool()
      }
    })
    
    // 监听API Key变化，保存到localStorage
    const { watch } = require('vue')
    watch(apiKey, (newValue) => {
      if (newValue) {
        localStorage.setItem('aiApiKey', newValue)
      }
    })
    
    return {
      // 配置
      apiKey,
      aiToolStatus,
      handleInitAiTool,
      
      // 流式输出
      streamInput,
      streamOutput,
      streamLoading,
      handleStreamChat,
      
      // 文档生成
      docTopic,
      docType,
      docAudience,
      documentOutput,
      docLoading,
      handleGenerateDocument,
      
      // 文档润色
      polishInput,
      polishStyle,
      polishOutput,
      polishLoading,
      handlePolishDocument,
      
      // 健康规划
      userInfo,
      healthOutput,
      healthLoading,
      handleGenerateHealthPlan
    }
  }
}
</script>

<style scoped>
.ai-document-demo {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.demo-section, .config-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fff;
}

.input-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.input-group .el-input, .input-group .el-select {
  flex: 1;
  min-width: 150px;
}

.user-info {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
  width: 100%;
}

.user-info .el-input {
  flex: 1;
  min-width: 120px;
}

.output-box {
  min-height: 100px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.output-content {
  white-space: pre-wrap;
  line-height: 1.5;
}

.placeholder {
  color: #909399;
  font-style: italic;
}

.status-message {
  padding: 10px;
  border-radius: 4px;
  margin-top: 10px;
}

.status-message.success {
  background-color: #f0f9ff;
  color: #409eff;
  border: 1px solid #b3d8ff;
}

.status-message.error {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fbc4c4;
}
</style>